<template>
<div class="user">
  <!-- 面包屑导航区 -->
  <el-breadcrumb>
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    <el-breadcrumb-item>用户列表</el-breadcrumb-item>
  </el-breadcrumb>
  <!-- 卡片试图区 -->
  <el-card class="box-card">
    <!-- 搜索与添加区域 -->
    <el-row :gutter="20">
      <el-col :span="10">
        <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
          <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
        </el-input>
      </el-col>

      <el-col :span="6">
        <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
      </el-col>
    </el-row>
    <!-- 用户列表区域 -->
    <el-table :data="userList" border stripe>
      <el-table-column type="index"></el-table-column>
      <el-table-column label="姓名" prop="username"></el-table-column>
      <el-table-column label="邮箱" prop="email"></el-table-column>
      <el-table-column label="电话" prop="mobile"></el-table-column>
      <el-table-column label="角色" prop="role"></el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.state" active-color="#13ce66" inactive-color="#ff4949" @change="userStateChanged(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <!-- 插槽作用域 -->
        <template slot-scope="scope">
          <!-- 修改按钮 -->
          <el-tooltip effect="dark" content="修改" placement="top" :enterable="false">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row._id)"></el-button>
          </el-tooltip>
          <!-- 删除按钮 -->
          <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row._id)"></el-button>
          </el-tooltip>
          <!-- 分配角色按钮 -->
          <el-tooltip effect="dark" content="设置" placement="top" :enterable="false">
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 3, 5]" :page-size="queryInfo.pagesize" background layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
  </el-card>
  <!-- 添加用户的提示 -->
  <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
    <!-- 内容主体区域 -->
    <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model.trim="addForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model.trim="addForm.password"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model.trim="addForm.email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input v-model.trim="addForm.mobile"></el-input>
      </el-form-item>
    </el-form>
    <!-- 底部区域 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="addDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addUser">确 定</el-button>
    </span>
  </el-dialog>

  <!-- 修改用户表单 -->
  <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
    <!-- 主体内容 -->
    <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
      <el-form-item label="用户名">
        <el-input v-model.trim="editForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model.trim="editForm.email"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model.trim="editForm.mobile"></el-input>
      </el-form-item>
    </el-form>
    <!-- 底部按钮 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="editDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="editUserInfo">确 定</el-button>
    </span>
  </el-dialog>

  <!-- 分配角色的对话框 -->
  <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close="setRoleDialogClosed">
    <div>
      <p>当前用户:</p>
      <p>当前用户:</p>
      <p>分配新角色:
        <el-select v-model="selectedRoleId" placeholder="请选择">
    <el-option
      v-for="item in roleList"
      :key="item.value"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>
      </p>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="setRoleDialogVisible = false">取 消</el-button>
      <el-button type="primary"  @click="saveRoleInfo">确 定</el-button>
    </span>
  </el-dialog>

</div>
</template>

<script>
export default {
  name: "user",
  created() {
    this.getUserList();
  },
  data() {
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: "",
        // 当期的页数
        pagenum: 1,
        // 当前每页的数量
        pagesize: 2
      },
      // 获取的总数
      total: 0,
      userList: [],
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 添加用户表单
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
        role: "普通用户",
        state: true
      },
      // 添加表单验证的规则对象
      addFormRules: {
        username: [{
            required: true,
            message: "请输入用户名",
            trigger: "blur"
          },
          {
            min: 2,
            max: 10,
            message: "用户名长度在2~10之间",
            trigger: "blur"
          }
        ],
        password: [{
            required: true,
            message: "请输入密码",
            trigger: "blur"
          },
          {
            min: 6,
            max: 15,
            message: "密码长度在6~15之间",
            trigger: "blur"
          }
        ],
        email: [{
            required: true,
            message: "请输入邮箱",
            trigger: "blur"
          },
          {
            type: "email",
            message: "请输入正确的邮箱！",
            trigger: "blur"
          }
        ],
        mobile: [{
            required: true,
            message: "请输入手机号",
            trigger: "blur"
          },
          {
            pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
            message: "输入正确的手机号",
            trigger: "blur"
          }
        ]
      },

      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 要修改的用户信息
      editForm: {
        email: "",
        mobile: ""
      },
      // 表单的验证规则对象
      editFormRules: {
        email: [{
            required: true,
            message: "请输入邮箱",
            trigger: "blur"
          },
          {
            type: "email",
            message: "请输入正确的邮箱！",
            trigger: "blur"
          }
        ],
        mobile: [{
            required: true,
            message: "请输入手机号",
            trigger: "blur"
          },
          {
            pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
            message: "输入正确的手机号",
            trigger: "blur"
          }
        ]
      },
      // 控制是否显示分配角色的对话框
      setRoleDialogVisible: false,
      // 需要被分配的用户角色信息
      userinfo: null,
      // 所有角色的数据列表
      roleList: [],
      // 已选中角色的ID值
      selectedRoleId: [],
    };
  },
  methods: {
    async getUserList() {
      let anonymousLogin = await this.$login();
      // 若匿名登录失败就直接停止了
      if (!anonymousLogin) return;
      let res = await this.$cloudbase.callFunction({
        name: "user",
        data: {
          methods: "get",
          data: this.queryInfo
        }
      });
      this.userList = res.result.data;
    },
    // 获取最小的分页菜单
    async handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      // 当页码数发生改变时，重新发送请求
      this.getUserList();
    },
    // 监听页面值的改变事件
    async handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      // 当页码条数发生改变时，重新发送请求
      this.getUserList();
    },
    // 改变开关触发事件
    async userStateChanged(userinfo) {
      let anonymousLogin = await this.$login();
      // 若匿名登录失败就直接停止了
      if (!anonymousLogin) return;
      let res = await this.$cloudbase.callFunction({
        name: "user",
        data: {
          methods: "update",
          id: userinfo._id,
          state: userinfo.state
        }
      });
      //若返回的数据存在id则表示修改成功了
      if (res.result.requestId) {
        return this.$message.success(`用户状态更新成功了`);
      }
      return this.$message.error(`用户更新状态失败`);
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      // 重置表单数据
      this.$refs.addFormRef.resetFields();
    },
    // 点击按钮，添加新用户
    async addUser() {
      this.$refs.addFormRef.validate(async value => {
        if (!value) return;
        // 验证通过后可以发起网络请求并添加用户了
        let anonymousLogin = await this.$login();
        // 若匿名登录失败就直接停止了
        if (!anonymousLogin) return;
        let res = await this.$cloudbase.callFunction({
          name: "user",
          data: {
            methods: "add",
            data: this.addForm
          }
        });
        if (!res.result.id) {
          return this.$message.error(`添加用户失败`);
        }
        this.$message.success(`添加用户成功`);
        // 关闭添加用户窗口
        this.addDialogVisible = false;
        // 重新获取数据
        this.getUserList();
      });
    },
    // 展示编辑用户的对话框
    async showEditDialog(id) {
      let anonymousLogin = await this.$login();
      // 若匿名登录失败就直接停止了
      if (!anonymousLogin) return;
      let res = await this.$cloudbase.callFunction({
        name: "user",
        data: {
          methods: "editQuery",
          data: id
        }
      });
      this.editForm = res.result.data[0];
      this.editDialogVisible = true;
    },
    // 重置修改用户信息的表单内容了
    editDialogClosed() {
      // 重置表单数据
      this.$refs.editFormRef.resetFields();
    },
    // 修改信息并提交
    async editUserInfo() {
      this.$refs.editFormRef.validate(async value => {
        if (!value) return;
        // 发起修改信息的请求了
        let anonymousLogin = await this.$login();
        // 若匿名登录失败就直接停止了
        if (!anonymousLogin) return;
        let res = await this.$cloudbase.callFunction({
          name: "user",
          data: {
            methods: "editUserInfo",
            data: this.editForm
          }
        });
        if (!res.result.requestId) {
          this.$message.error(`修改失败`);
        }
        this.$message.success(`修改成功了`);
        // 刷新数据
        this.getUserList();
        // 关闭修改信息框
        this.editDialogVisible = false;
      });
    },
    // 根据id来删除用户
    async removeUserById(id) {
      // 弹框询问用户是否删除
      let resCon = await this.$confirm("是否删除该用户", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(err => err);
      // 用户点击了取消按钮时
      if (resCon === "cancel") {
        return this.$message.info(`已经取消删除`);
      }
      // 用户点击了确定按钮了
      let anonymousLogin = await this.$login();
      // 若匿名登录失败就直接停止了
      if (!anonymousLogin) return;
      let res = await this.$cloudbase.callFunction({
        name: "user",
        data: {
          methods: "removeUserById",
          data: id
        }
      });
      if (res.result.deleted == 1) {
        // 刷新数据列表
        this.getUserList();
        this.$message.success(`删除成功了`);
      }
    },

    // 展示分配角色的对话框
    async setRole(userinfo){
      this.userinfo = userinfo;
      // 展示对话框之前获取所有的角色列表
      // 发送请求获取数据
      // this.roleList =
      this.setRoleDialogVisible = true;
    },

    // 点击按钮分配角色
    async saveRoleInfo(){
      if(!this.selectedRoleId){
        return this.$message.error(`请选择要分配的角色!`);
      };
      this.setRoleDialogVisible = false;
    },
    // 监听角色对话框的关闭事件
    setRoleDialogClosed(){
      this.selectedRoleId = "";
      this.userinfo = {};
    },
  }
};
</script>

<style lang="less" scoped>
</style>
